package XML与JSON.使用JACKSON;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;

import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.core.exc.StreamReadException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

import lombok.Data;
import lombok.ToString;

public class 解析xml {//解析成实例对象  xml ---> 实例对象
	@Test
   void test() throws StreamReadException, DatabindException, IOException {
   	InputStream input = 解析xml.class.getResourceAsStream("book.xml");//不带路径表示在当前类所在包下获取资源流
   	//URI uri = URI.create("book.xml");
   	//System.out.println(uri.getSchemeSpecificPart());//book.xml
	
   	JacksonXmlModule moudle = new JacksonXmlModule();
   	XmlMapper mapper = new XmlMapper(moudle);
   	mapper.enable(SerializationFeature.INDENT_OUTPUT);//xml多行带缩进格式
   	Book book = mapper.readValue(input, Book.class);
   	System.out.println(book);//Book(id=1, name=Java核心技术, author=Cay S. Horstmann, isbn=1234567, tags=[Java, Network], pubDate=)
   	System.out.println(book.name);//Java核心技术
   }
}

//注意到XmlMapper​​就是我们需要创建的核心对象，可以用readValue(InputStream, Class)​​直接读取XML并返回一个JavaBean。

@Data
@ToString
class Book {
	@JacksonXmlProperty(isAttribute=true)//id为节点的属性
    public long id;
    public String name;
    public String author;
    public String isbn;
    public List<String> tags;
    public String pubDate;

//    @Override
//    public String toString() {
//        return "Book{" +
//                "id=" + id +
//                ", name='" + name + '\'' +
//                ", author='" + author + '\'' +
//                ", isbn='" + isbn + '\'' +
//                ", tags=" + tags +
//                ", pubDate='" + pubDate + '\'' +
//                '}';
//    }
}

/*
<?xml version="1.0" encoding="UTF-8" ?>
<book id="1">
    <name>Java核心技术</name>
    <author>Cay S. Horstmann</author>
    <isbn lang="CN">1234567</isbn>
    <tags>
        <tag>Java</tag>
        <tag>Network</tag>
    </tags>
    <pubDate/>
</book>
*/